<template>
  <div>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>文章列表</span>
    </div>
    <el-form>
      <el-row>
        <el-col :span="5">
          <el-form-item label="文章分类">
            <ChannelSelect v-model="params.cate_id"></ChannelSelect>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="文章列表">
            <el-select placeholder="请选择状态" class="select-height" v-model="params['state']">
              <el-option
                v-for="item in articleStateList"
                :key="item.id"
                :value="item.name"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" size="small" class="btn-height" @click="searchArticle">筛选</el-button>
          <el-button type="info" size="small" class="btn-height" @click="resetForm">重置</el-button>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" size="small" class="btn-height" @click="openDrawer('add')">发表文章</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table
    :data="tableData"
    stripe
    border
    style="width: 100%">
    <el-table-column
      label="文章标题"
      prop="title"
      fit
      >
      <template #default="{row}">
        <el-link type="primary" :underline="false">{{ row.title }}</el-link>
      </template>
    </el-table-column>
    <el-table-column
      fit
      label="分类"
      prop="cate_name"
      >
    </el-table-column>
    <el-table-column
      fit
      label="发表时间"
      prop="pub_date"
     >
     <template #default="{row}">
     {{ formatTime(row.pub_date) }}
     </template>
    </el-table-column>
    <el-table-column
      fit
      label="状态"
      prop="state"
     >
    </el-table-column>
    <el-table-column label="操作">
      <!-- scope的row属性可以拿到本行数据 -->
      <template #default="{row}">
        <el-button
        @click="delArticle(row.id)"
          size="mini"
          type="danger">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
  </el-card>
  <el-drawer
  :title="drawerTitle"
  direction="ttb"
  :visible.sync="isShowDrawer"
  :before-close="handleClose"
  size="100%"
  append-to-body
  >
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="文章标题" prop="title">
      <el-input placeholder="请输入标题" v-model="form.title"></el-input>
    </el-form-item>
    <el-form-item label="文章分类" prop="cate_id">
      <ChannelSelect v-model="form.cate_id"></ChannelSelect>
    </el-form-item>
    <el-form-item label="文章内容" prop="content">
      <quillEditor
      ref="editor"
      @blur="$refs.form.validateField('content')"
      v-model="form.content"
      contentType="html"
      ></quillEditor>
    </el-form-item>
    <el-form-item label="封面" style="margin-top: 80px;">
        <!-- 需要关闭elementui自动上传，不需要配置 action等参数
              只需要做前端的本地预览图片即可，无需在提交前上传图标
            语法：URL.createObjectURL（...）创建本地预览的地址，来预览 -->
            <el-upload
              :on-change="onSelectFile"
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              style="width: 400px; height: 280px; border: 1px solid #ccc; border-radius: 4px; overflow: hidden; position: relative;">
              <img v-if="imgUrl" :src="imgUrl" class="avatar" style="width: 100%; height: 100%; object-fit: cover;">
              <i v-else class="el-icon-plus avatar-uploader-icon" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></i>
          </el-upload>

      <!-- <img src="../../assets/images/cover.jpg" alt=""> -->
    </el-form-item>
    <el-form-item>
      <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
      <el-button @click="onPublish('草稿')" type="info">存为草稿</el-button>
    </el-form-item>
  </el-form>
  </el-drawer>
</div>
</template>

<script>
import dayjs from 'dayjs'
import { getArticleListAPI, publishArticleAPI, delArticleAPI } from '@/api/article'
import { mapState } from 'vuex'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import ChannelSelect from './components/ChannelSelect.vue'

export default {
  name: 'art-list',
  data () {
    return {
      tableData: [],
      params: {
        pagenum: 1, // 页码
        pagesize: 2, // 数据条数
        state: '', // 状态
        cate_id: ''
      },
      total: 0, // 总的页数
      articleStateList: [
        {
          id: 'over',
          name: '已发布'
        },
        {
          id: 'cg',
          name: '草稿'
        }

      ],
      drawerType: 'add',
      isShowDrawer: false, // 抽屉状态
      imgUrl: '',
      // 默认表单数据
      defaultForm: {
        title: '', // 标题
        cate_id: '', // 分类id
        cover_img: '', // 封面图片 file对象
        content: '', // string内容
        state: '' // 发布状态
      },
      form: {
        ...this.defaultForm
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择标题', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }

        ]
      }
    }
  },
  components: {
    quillEditor,
    ChannelSelect
  },
  mounted () {
    // 渲染列表
    this.getArticleList()
  },
  computed: {
    ...mapState('article', ['artcate']),
    drawerTitle () {
      let title = '发布文章'
      if (this.drawerType === 'add') title = '发布文章'
      if (this.drawerType === 'preview') title = '文章预览'
      return title
    }
  },
  methods: {
    async getArticleList () {
      const res = await getArticleListAPI(this.params)
      // this.tableData = res.data
      this.tableData = [...res.data]
      this.total = res.total
    },
    // 每页要展示的条数发生改变
    handleSizeChange (val) {
      this.params.pagesize = val
      // 重新渲染
      this.getArticleList()
    },
    // 当前页数发生改变
    handleCurrentChange (val) {
      this.params.pagenum = val
      this.getArticleList()
    },
    // 筛选
    searchArticle () {
      this.params.pagenum = '1'
      this.getArticleList()
    },
    // 重置数据
    resetForm () {
      this.params.pagenum = '1'
      this.params.state = ''
      this.params.cate_id = ''
      this.getArticleList()
    },
    // 打开抽屉
    openDrawer (type, id) {
      this.drawerType = type
      this.isShowDrawer = true
      if (id) {
        console.log('预览状态')
      } else {
        this.form = { ...this.defaultForm }// 重置form数据
        this.imgUrl = ''
        this.$refs.editor.setHTML('')
      }
    },
    handleClose () {
      // 关闭前的回调函数：一但配置了这个回调，他就不会自动关闭了
      this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示', {
        type: 'warning'
      }).then(() => {
        this.closeDrawer()
      }).catch(() => {
        console.log('取消')
      })
    },
    closeDrawer () {
      this.isShowDrawer = false
    },
    // 上传图片
    onSelectFile (uploadFile) {
      this.imgUrl = URL.createObjectURL(uploadFile.raw) // 预览图片
      this.form.cover_img = uploadFile.raw
    },
    // 提交
    async onPublish (state) {
      // 将状态存入form中
      this.form.state = state
      // 统一校验
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 当前接口需要formData对象
          // 将对象=》formData对象
          const fd = new FormData()
          for (const key in this.form) {
            fd.append(key, this.form[key])
          }
          await publishArticleAPI(fd)
          this.$message.success('发布文章成功')
          this.isShowDrawer = false
          // 会渲染到最后一条去
          const lastPage = Math.ceil((this.total + 1) / this.params.pagesize)
          this.params.pagenum = lastPage
          this.getArticleList()
        } else {
          console.log('error')
        }
      })
    },
    delArticle (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delArticleAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.params.pagenum = 1
        this.getArticleList()
      }).catch(() => {
        console.log('')
      })
    },
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  }

}
</script>

<style lang="less" scoped>
.select-height,
.btn-height {
  height: 32px; /* 调整为按钮的高度 */
}
.text-right {
  text-align: right;
}
.el-drawer__container {
   /* 调整左右内边距 */
  .select-height,
.btn-height,
.el-input,
.quill-editor,
.el-select {
  width: calc(100% - 40px); /* 考虑到左右内边距各占 20px，减去 40px */
}
}
.quill-editor{
  height: 300px;
}
img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
